package alkaid.eis.common.util;

import static org.springframework.util.StringUtils.hasText;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import lombok.experimental.UtilityClass;

/**
 * 字符创帮助类
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class StringHelper {
    public String limitLength(String strValue, int byteLen) {
        if (!hasText(strValue)) {
            return strValue;
        }

        int realLen = byteLen <= 0 ? 0 : byteLen;
        byte[] utf8Bytes = strValue.getBytes(StandardCharsets.UTF_8);
        if (realLen > utf8Bytes.length) {
            return strValue;
        }
        return new String(strValue.getBytes(), 0, realLen, StandardCharsets.UTF_8);
    }

    /**
     * 转换成UTF-8的字符集
     * @param target
     * @return
     */
    public String toUtf8(String target) {
        ByteBuffer buffer = StandardCharsets.UTF_8.encode(target);
        return StandardCharsets.UTF_8.decode(buffer).toString();
    }

}
